<template>
  <div>
    <div class="xExcel" :id="id" :style="{height: height}"></div>
  </div>
</template>

<script lang="ts">
import {defineComponent, onMounted, watch, ref, nextTick, onBeforeUnmount} from 'vue';
import Spreadsheet from "x-data-spreadsheet";
// import zhCN from 'x-data-spreadsheet/dist/locale/zh-cn';
export default defineComponent({
  name: 'xExcel',
  props: {
    id: {
      type: String,
      default() {
        return "x-spreadsheet-dom"
      }
    },
    action: {
      type: String,
      default() {
        return "edit"
      }
    },
    height: {
      type: String,
      default() {
        return "calc(100vh - 170px)"
      }
    },
    cells: {
      type: Object,
      default() {
        return null
      }
    }
  },
  setup(props, {emit}) {
    const xExcelObj = ref(null)
    const excelData = ref(null)
    onMounted(() => {
      nextTick(() => {
        initMindMap();
      });
    });
    watch(() => props.cells, (newVal) => {
      if (newVal?.hasOwnProperty('name')) {
        xExcelObj.value.loadData(newVal);
      }
    })
    const initMindMap = () => {
      xExcelObj.value = new Spreadsheet(
          "#" + props.id,
          {
            mode: props.action, // edit | read
            showToolbar: props.action === 'edit',
            showGrid: true,
            showContextmenu: props.action === 'edit',
            view: {
              // height: () => document.documentElement.clientHeight,
              height: () => document.documentElement.clientHeight - 200,
              width: () => document.documentElement.clientWidth,
            },
            row: {
              len: 50,
              height: 25,
            },
            col: {
              len: 26,
              width: 100,
              indexWidth: 60,
              minWidth: 60,
            },
            style: {
              bgcolor: '#ffffff',
              align: 'left',
              valign: 'middle',
              textwrap: false,
              strike: false,
              underline: false,
              color: '#0a0a0a',
              font: {
                name: 'Helvetica',
                size: 10,
                bold: false,
                italic: false,
              },
            },
          })
          .loadData(props.cells?.hasOwnProperty('name') ? props.cells : {}) // load data
          .change(data => {
            excelData.value = data
          });
      // xExcelObj.value.locale('zh-cn', zhCN);
    }
    const getExcelData = () => {
      return excelData.value
    }
    const refreshMindMapData = (data: object) => {
      // return mind.value.refresh(data)
    }
    const exportAsPicture = async (type: string) => {

    }
    onBeforeUnmount(() => {
      xExcelObj.value = null
    })
    return {
      getExcelData,
      exportAsPicture,
      refreshMindMapData,
    }
  }
});
</script>

<style scoped lang="scss">
.xExcel {
  width: 100%;
}
</style>
